package com.gzsxy.esjy.service.core.sign.service.doc;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;

import com.gzsxy.esjy.common.base.exception.impl.BusinessException;
import com.gzsxy.esjy.feign.NettyFile.FileService;
import com.gzsxy.esjy.service.base.DictionaryConstants;
import com.gzsxy.esjy.service.base.dto.request.UploadRequest;
import com.gzsxy.esjy.service.base.dto.response.DefaultResponse;
import com.gzsxy.esjy.service.core.sign.dto.DocumentSignDto;
import com.gzsxy.esjy.service.core.sign.entity.ArraignSign;
import com.gzsxy.esjy.service.core.sign.entity.ResourcesIndex;
import com.gzsxy.esjy.service.core.util.PdfUtils;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.PdfReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;

import java.util.List;

/**
 * @author zhangxiaolong
 * @date 2022/7/13 11:36
 */
@ConditionalOnProperty(name = "document.diy.area", havingValue = "chongqing")
@Component
@Slf4j
public class ChongqingImpl extends DocBaseService implements DocHandleService {
    @Autowired
    private FileService  fileService;

    /**
     * 重庆文书生成
     *
     * @param arraignSign
     * @param startTime
     * @param endTime
     * @param content
     * @param signFileIndex
     * @return
     */
    @Override
    public void doSign(ArraignSign arraignSign, String startTime, String endTime, String content, File pdfFile,String sealFileType) {
    }



    /**
     * 文书盖章
     *
     * @param arraignSign
     * @param documentSignDto
     * @param sealFilePath    盖章文件的绝对路径
     * @param pdfFile         未盖章的源文件
     * @param pdfFileType     文件格式
     */
    @Override
    public void doSeal(ArraignSign arraignSign, DocumentSignDto documentSignDto, String sealFilePath, File pdfFile, String pdfFileType) {
        log.info("重庆盖章----documentSignDto---" + JSON.toJSONString(documentSignDto));


    }



    /**
     * 前端传入比例，换算pdf真实坐标
     *
     * @param pdf
     * @param pdfFile
     */
    private void setRealCoordinate(PdfUtils.PdfMark pdf, File pdfFile) {
        PdfReader pdfreader;
        Document document = null;
        try {
            pdfreader = new PdfReader(pdfFile.getPath());
            document = new Document(pdfreader.getPageSize(pdf.getPdfPage()));
        } catch (Exception e) {
            log.error("setRealCoordinate 获取pdf真实坐标失败：{}", e.getMessage());
        }
        // 获取页面宽度
        float width = document != null ? document.getPageSize().getWidth() : 0;
        pdf.setX(width * pdf.getX());
        // 获取页面高度
        float height = document != null ? document.getPageSize().getHeight() : 0;
        pdf.setY(height * (1 - pdf.getY()));

        log.info("pdf ---x" + pdf.getX());
        log.info("pdf ---y" + pdf.getY());
    }

    /**
     * 合成pdf并上传file-server，然后更新latestFile字段
     *
     * @param pdfFile     未盖章的源文件
     * @param list        pdf需要合成列表
     * @param pdfFileType 文件格式
     * @param arraignSign
     */
    private void handlePdf(File pdfFile, List<PdfUtils.PdfMark> list, String pdfFileType, ArraignSign arraignSign) {
        String sealPdfPath = String.format("%s/seal/%s%s", DictionaryConstants.PDF_TEMP_PATH, UUID.randomUUID().toString(), pdfFileType);
        File sealPdfFile = new File(sealPdfPath);

        log.info("handlePdf---" + JSON.toJSONString(list));

        boolean markOnTop = PdfUtils.addPdfMarkOnTop(pdfFile, sealPdfFile, list, DictionaryConstants.NUMBER_12, Element.ALIGN_CENTER);
        if (!markOnTop) {
            throw BusinessException.getInstance("盖章失败");
        }

        String fileIndex = this.upload(sealPdfPath, null);
        arraignSign.setLatestFile(fileIndex);
        sealPdfFile.delete();
        pdfFile.delete();
    }


    /**
     * 通过base64上传到file-server
     * @param path
     * @param fileName
     * @return
     */
    public String upload(String path,String fileName){
        File pdfFile = new File(path);
        ResourcesIndex resourcesIndex =null;
        try {
            String encode = Base64.encode(pdfFile);
            UploadRequest uploadDto = new UploadRequest();
            uploadDto.setFileName("pdf");
            uploadDto.setContent(encode);
            uploadDto.setExpired(DictionaryConstants.NUMBER_0);
            if (!StringUtils.isEmpty(fileName)){
                uploadDto.setIndex(fileName);
            }
            DefaultResponse defaultResponse = fileService.uploadJson(uploadDto);
            resourcesIndex = JSON.parseObject(JSON.toJSONString(defaultResponse.getData()), ResourcesIndex.class);
        } catch (Exception e) {
            log.error("上传文件到file-server失败",e);
            BusinessException.getInstance("上传文件到file-server失败");
        }
        return resourcesIndex.getFileIndex();
    }
}
